package com.meila.cms.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.meila.cms.auth.AuthClass;
import com.meila.cms.auth.AuthMethod;
import com.meila.cms.dto.AjaxObj;
import com.meila.cms.entity.Role;
import com.meila.cms.entity.User;
import com.meila.cms.entity.UserRole;
import com.meila.cms.model.CommonModel;
import com.meila.cms.model.ResetPwdModel;
import com.meila.cms.model.RoleType;
import com.meila.cms.model.UserModel;
import com.meila.cms.services.ILoginService;
import com.meila.cms.services.IRoleService;
import com.meila.cms.services.IUserService;
import com.meila.cms.util.Captcha;
import com.meila.cms.web.CmsSessionContext;

@Controller
@RequestMapping("/before")
@AuthClass
public class LoginController extends BaseController {
	
	private IUserService userService;
	private IRoleService roleService;
	private ILoginService loginService;

	public IUserService getUserService() {
		return userService;
	}

	@Inject
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IRoleService getRoleService() {
		return roleService;
	}

	@Inject
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
	
	public ILoginService getLoginService(){
		return loginService;
	}
	
	@Inject
	public void setLoginService(ILoginService loginService){
		this.loginService = loginService;
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "index/register";
	}
	
	/**
     * 获取手机验证码
     * @return
     */
	@RequestMapping(value = "/register/getVerifyCode", method = RequestMethod.POST)
	@ResponseBody
	public CommonModel getVerifyCode(String phone){
		
		return loginService.getVerifyCode(request,phone);
		
	}
	
	/**
     * 验证手机号码的唯一性
     * @param phone
     * @return
     */
	@RequestMapping(value = "/register/uniqueVerify", method = RequestMethod.POST)
	@ResponseBody
	public CommonModel uniqueVerify(CommonModel commonModel){
		
		return loginService.uniqueVerify(commonModel);
		
	}
	
	/**
     * 动态码验证
     * @param phone
     * @return
     */
	@RequestMapping(value = "/register/dynamiccodeVerify", method = RequestMethod.POST)
	@ResponseBody
	public CommonModel dynamiccodeVerify(@RequestParam(value = "dynamiccode")String dynamiccode,
    		@RequestParam(value = "phone")String phone){
		
		return loginService.dynamiccodeVerify(dynamiccode,phone);
		
	}
	
	/**
     * 保存注册
     * @return
     */ 
	@RequestMapping(value = "/register/save_register", method = RequestMethod.POST)
	@ResponseBody
	public Boolean save_register(UserModel user){
		
		return loginService.save_register(user);
		
	}
	
	@RequestMapping(value = "/forgetPass", method = RequestMethod.GET)
	public String forgetPass() {
		return "index/forgetPass";
	}
	
	@RequestMapping(value = "/forgetPass2", method = RequestMethod.GET)
	public String forgetPass2(String phone,Model model) {
		
		model.addAttribute("phone",phone);
		
		return "index/forgetPass2";
	}
	
	/*
	 * 重置密码
	 * @return
	 */
	@RequestMapping(value ="/forgetpass/resetPass", method = RequestMethod.POST)
	@ResponseBody
	public CommonModel resetPass(ResetPwdModel resetPwdModel){
		
		return  loginService.updatePass(session,resetPwdModel);
		
	}
 
	@RequestMapping(value = "/copyright", method = RequestMethod.GET)
	public String copyright() {
		return "common/copyright";
	}
 
	@RequestMapping(value = {"/","/login"}, method = RequestMethod.GET)
	public String login() {
		return "index/login";
	}
	
	@RequestMapping(value = {"/","/login"}, method = RequestMethod.POST)
	@ResponseBody
	public AjaxObj login(String phone, String password,
			Model model, HttpSession session) {
 
		AjaxObj ajaxObj = userService.login(phone, password);
		if(ajaxObj.isResult()){
			
			UserModel user=(UserModel) ajaxObj.getObj();
	
			List<UserRole> urs = userService.listUserRoles(user.getId());
			// 获取角色列表集合
			List<Role> rs = roleService.listRole(urs);
			
			user.setAdmin(roleService.isAdmin(rs));
			
			session.setAttribute("allActions", getAllActions(rs, session));
			session.setAttribute("loginUser", user);
			session.setAttribute("roleList", rs);
			CmsSessionContext.addSessoin(session);
		}
 
		return ajaxObj;
	}
	
	
	@AuthMethod
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		logger.error("LoginController /logout");
		CmsSessionContext.removeSession(session);
		session.invalidate();
		return "redirect:/before/login";
	}

	@SuppressWarnings("unchecked")
	private Set<String> getAllActions(List<Role> rs, HttpSession session) {
		Set<String> actions = new HashSet<String>();
		Map<String, Set<String>> allAuths = (Map<String, Set<String>>) session
				.getServletContext().getAttribute("allAuths");
		if(allAuths.get("base")!=null){
			actions.addAll(allAuths.get("base"));
		}

		for (Role r : rs) {
			if (r.getRoleType() == RoleType.ROLE_ADMIN)
				continue;
			
			if(allAuths.get(r.getRoleType().name())!=null){
				actions.addAll(allAuths.get(r.getRoleType().name()));
			}
			
		}
		return actions;
	}

	private boolean isRole(List<Role> rs, RoleType rt) {
		for (Role r : rs) {
			if (r.getRoleType() == rt)
				return true;
		}
		return false;
	}

	
	/**
	 * 生成验证码(暂时没用)
	 * @param resp
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping("/drawCheckCode")
	public void drawCheckCode(HttpServletResponse resp, HttpSession session)
			throws IOException {
		resp.setContentType("image/jpg");
		int width = 200;
		int height = 30;
		Captcha c = Captcha.getInstance();
		c.set(width, height);
		String checkcode = c.generateCheckcode();
		session.setAttribute("cc", checkcode);
		OutputStream os = resp.getOutputStream();
		ImageIO.write(c.generateCheckImg(checkcode), "jpg", os);
	}
}
